import re
from typing import Dict, Any, Optional

from utils.config_manager import NetworkConfigManager


class NetworkConfigModel:
    """网络配置数据模型"""

    def __init__(self):
        self.config_manager = NetworkConfigManager()
        self.internal_config = self.config_manager.get_network_config("internal") or {"dhcp": True}
        self.external_config = self.config_manager.get_network_config("external") or {"dhcp": True}

    def get_config(self, network_type: str) -> Dict[str, Any]:
        """获取指定网络类型的配置"""
        if network_type == "internal":
            return self.internal_config.copy()
        elif network_type == "external":
            return self.external_config.copy()
        return {}

    def validate_ip(self, ip: str) -> bool:
        """验证IP地址格式"""
        if not ip:
            return True

        pattern = r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$"
        match = re.match(pattern, ip)
        if not match:
            return False

        return all(0 <= int(octet) <= 255 for octet in match.groups())

    def save_config(self, network_type: str, config: Dict[str, Any]) -> bool:
        """保存网络配置"""
        try:
            self.config_manager.set_network_config(network_type, config)
            if network_type == "internal":
                self.internal_config = config.copy()
            elif network_type == "external":
                self.external_config = config.copy()
            return True
        except Exception:
            return False